import { useEffect, useState } from 'react'
import { useRecoilValue } from 'recoil'
import { message } from 'antd'
import { ReportReview, ReportChat } from '../data'
import { CardList } from '@/@types'
import { deportDataExport, getTableList } from '../service'
import { isNullArray, isNullData, exportData } from '@/utils'
import { theQuarterData } from '@/store/user'

export default (): ReportReview => {
  const quarterData = useRecoilValue(theQuarterData)
  // console.log('quarterData🚀🚀🚀🚀', quarterData)
  // 卡片信息
  const [cardList, setCardList] = useState<CardList[]>([])

  // 当前选中任务
  const [task, setTask] = useState<Array<string>>(
    isNullArray(quarterData) ? [quarterData[0].value, quarterData![0].children![0].value] : [],
  )

  // 存放表格数据
  const [tableList, setTableList] = useState<ReportChat[]>([])
  // 存放表格加载效果
  const [tableLoading, setTableLoading] = useState<boolean>(false)

  // 获取数据
  const getTables = async () => {
    setTableLoading(true)
    const res = await getTableList({
      dataReportYear: task[0] ? task[0] : '',
      dataReportQuarter: task[1] ? task[1] : '',
    })
    if (isNullData(res) && res.data && isNullArray(res.data)) {
      setCardList(res.data.dataEscalationHeads)
      setTableList(res.data.dataEscalationBottoms)
    } else {
      setCardList([])
      setTableList([])
    }
    setTableLoading(false)
    console.log('res🚀🚀🚀🚀', res)
  }

  // 任务下拉框变化时触发
  const handleTaskChange = (e: Array<string>) => {
    setTask(e)
  }

  // 导出
  const exportReview = async () => {
    const res = await deportDataExport({
      dataReportQuarter: task[1] ? task[1] : '',
      dataReportYear: task[0] ? task[0] : '',
    })
    exportData(res, `${task[0]}年第${task[1]}季度`, 'xlsx')
    message.success('导出成功')
    console.log('res🚀🚀🚀🚀', res)
  }

  useEffect(() => {
    if (task) {
      getTables()
    }
  }, [task])

  return {
    cardList,
    handleTaskChange,
    task,
    tableList,
    tableLoading,
    quarterData,
    exportReview,
  }
}
